package com.aiatomic.couting;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import com.aiatomic.couting.util.HttpUtils;
import com.aiatomic.couting.util.SystemUtil;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.widget.Toast;

public class SplashActivity extends Activity {

	private static final int W_MSG_MAIN = 0;
	private final int WRITE_EXTERNAL_STORAGE = 100;
	private final int CAMERA = 101;
	private final int ACCESS_NETWORK_STATE = 102;
	private Handler handler;
	Handler m_mainHandler;
	ProgressDialog m_progressDlg;

	private boolean isGranted(String permission) {
		int checkSelfPermission = ActivityCompat.checkSelfPermission(this, permission);
		return checkSelfPermission == PackageManager.PERMISSION_GRANTED;
	}

	private void requestPermission(String permission, int requestCode) {
		if (!isGranted(permission)) {
			ActivityCompat.requestPermissions(this, new String[] { permission }, requestCode);
		} else {
			// 直接执行相应操作了
		}
	}

/*	@Override
	public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
		if (requestCode == WRITE_EXTERNAL_STORAGE || requestCode == CAMERA) {
			if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
			} else {
				finish();
				Toast.makeText(SplashActivity.this, "您没有授权该权限，请在设置中打开授权", Toast.LENGTH_SHORT).show();
			}
			return;
		}
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
	}*/

	public void showNetDialog(final Context context) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);

		builder.setMessage("世界上最遥远的距离就是没网");
		builder.setPositiveButton("检查设置", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				Intent intent = null;
				try {
					@SuppressWarnings("deprecation")
					String sdkVersion = android.os.Build.VERSION.SDK;
					if (Integer.valueOf(sdkVersion) > 10) {
						intent = new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);
					} else {
						intent = new Intent();
						ComponentName comp = new ComponentName("com.android.settings",
								"com.android.settings.WirelessSettings");
						intent.setComponent(comp);
						intent.setAction("android.intent.action.VIEW");
					}
					context.startActivity(intent);
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		});

		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				SplashActivity.this.finish();
			}
		});

		builder.show();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);
		//requestPermission(Manifest.permission.ACCESS_NETWORK_STATE, ACCESS_NETWORK_STATE);
		if (SystemUtil.GetNetype(this) == -1) {
			showNetDialog(this);
		} else {
			initEvent();
			InitThread t = new InitThread();
			t.start();
		}
		m_mainHandler = new Handler();
		m_progressDlg = new ProgressDialog(this);
		m_progressDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		// 设置ProgressDialog 的进度条是否不明确 false 就是不设置为不明确
		m_progressDlg.setIndeterminate(false);
		m_progressDlg.setCancelable(false);
		m_progressDlg.setOnKeyListener(new DialogInterface.OnKeyListener() {

			@Override

			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event)

			{
				if (KeyEvent.KEYCODE_BACK == keyCode) {
					return false;
				}
				return false;
			}

		});

	}

	private void downFile(final String url) {
		m_progressDlg.show();
		new Thread() {
			public void run() {
				HttpClient client = new DefaultHttpClient();
				HttpGet get = new HttpGet(url);
				HttpResponse response;
				try {
					response = client.execute(get);
					HttpEntity entity = response.getEntity();
					final float length = entity.getContentLength();

					m_progressDlg.setMax((int) length);// 设置进度条的最大值
					m_mainHandler.post(new Runnable() {
						public void run() {
							m_progressDlg
									.setMessage("请稍等片刻，需要下载的文件大小约为:" + String.format("%.2f M", length / 1024 / 1024));
						}
					});
					InputStream is = entity.getContent();
					FileOutputStream fileOutputStream = null;
					if (is != null) {
						File file = new File(SplashActivity.this.getExternalCacheDir(), "Couting.apk");
						fileOutputStream = new FileOutputStream(file);
						byte[] buf = new byte[1024];
						int ch = -1;
						int count = 0;
						while ((ch = is.read(buf)) != -1) {
							fileOutputStream.write(buf, 0, ch);
							count += ch;
							if (length > 0) {
								m_progressDlg.setProgress(count);
							}
						}
					}
					fileOutputStream.flush();
					if (fileOutputStream != null) {
						fileOutputStream.close();
					}
					down();
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	private void down() {
		m_mainHandler.post(new Runnable() {
			public void run() {
				m_progressDlg.cancel();
				update();
			}
		});
	}

	void update() {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		if (Build.VERSION.SDK_INT >= 24) {
			intent.setDataAndType(
					FileProvider.getUriForFile(SplashActivity.this, "com.aiatomic.couting.fileprovider",
							new File(SplashActivity.this.getExternalCacheDir(), "Couting.apk")),
					"application/vnd.android.package-archive");
			intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		} else {
			intent.setDataAndType(Uri.fromFile(new File(SplashActivity.this.getExternalCacheDir(), "Couting.apk")),
					"application/vnd.android.package-archive");
		}
		startActivity(intent);
	}

	/**
	 * 提示更新新版本
	 */
	private void doNewVersionUpdate(String newVerName, final String downUrl, boolean isForce, String desc) {
		String verName = SystemUtil.getAppVersion(getApplicationContext());
		String str = "";
		if (!isForce) {
			str = "发现新版本：" + newVerName + ",是否更新？\n" + desc;
		} else {
			str = "发现新版本：" + newVerName + ",版本过期，请立即更新!\n" + desc;
		}
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("软件更新").setMessage(str)
				// 设置内容
				.setPositiveButton("更新", // 设置确定按钮
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								m_progressDlg.setTitle("正在下载");
								m_progressDlg.setMessage("大约");
								downFile(downUrl); // 开始下载
							}
						});
		if (!isForce) {
			builder.setNegativeButton("暂不更新", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					startActivity(new Intent(SplashActivity.this, MainActivity.class));
					SplashActivity.this.finish();
				}
			});
		}

		Dialog dialog = builder.create();// 创建
		dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {

			@Override

			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event)

			{
				if (KeyEvent.KEYCODE_BACK == keyCode) {
					return false;
				}
				return false;
			}

		});
		dialog.setCancelable(false);
		dialog.show();
	}

	private void ScheckVersion() {
		/*
		 * JSONArray goods=json.getJSONArray("goods"); for(int
		 * i=0;i<goods.length();i++){ JSONObject good=goods.getJSONObject(i);
		 * GoodEntity entity=new GoodEntity();
		 * entity.setSb_good_id(good.getString("sb_good_id"));
		 * entity.setDesc(good.getString("desc"));
		 * entity.setDiscount(good.getDouble("discount"));
		 * entity.setFirst_give(good.getInt("first_give"));
		 * entity.setGive_days(good.getInt("give_days"));
		 * entity.setIs_test(good.getBoolean("is_test"));
		 * entity.setName(good.getString("name"));
		 * entity.setPic(good.getInt("pic"));
		 * entity.setPlatform(good.getInt("platform"));
		 * entity.setPos(good.getInt("pos"));
		 * entity.setPrice(good.getDouble("price"));
		 * entity.setType(good.getInt("type")); AppUtils.goods.add(entity); }
		 */
	}

	/**
	 * 检查版本
	 * 
	 */
	private void checkVersion() {
		Map<String, String> params = new HashMap<String, String>();
		params.put("platform", String.valueOf(IConstant.PLATFORM));
		params.put("client_version", SystemUtil.getAppVersion(this));
		params.put("time", String.valueOf(Calendar.getInstance().getTimeInMillis()));
		params.put("sign", HttpUtils.md5(
				params.get("client_version") + params.get("platform") + params.get("time") + IConstant.NORMAL_MD5_KEY));
		HttpUtils.post(new Handler() {

			@Override
			public void handleMessage(Message msg) {
				if (msg.what == HttpUtils.CODE_SUCCESS_RQ_100) {
					try {
						JSONObject json = new JSONObject(msg.obj.toString());

						if (json.getInt("code") == HttpUtils.RET_SUCCESS) {
							String downUrl = json.getString("downloadUrl");
							if (downUrl.isEmpty()) {
								startActivity(new Intent(SplashActivity.this, LoginActivity.class));
								SplashActivity.this.finish();
							} else {
								doNewVersionUpdate(json.getString("newVer"), downUrl, json.getBoolean("is_force"),
										json.getString("newVerdesc"));
							}
						} else {
							Toast toast = Toast.makeText(SplashActivity.this, json.getString("msg"), Toast.LENGTH_LONG);
							toast.setGravity(Gravity.CENTER, 0, 0);
							toast.show();
						}
					} catch (JSONException e) {
						e.printStackTrace();
						Log.e("", msg.obj.toString());
						Toast toast = Toast.makeText(SplashActivity.this,
								SplashActivity.this.getResources().getString(R.string.server_format_error),
								Toast.LENGTH_LONG);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
						SplashActivity.this.finish();
					}
				} else {
					Toast toast = Toast.makeText(SplashActivity.this, ICodeMsg.ERROR_CODES_HTTP.get(msg.what),
							Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					SplashActivity.this.finish();
				}
			}

		}, IConstant.CENTER + "/v/cindex/check_version/", params);
	}

	private void initEvent() {
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case W_MSG_MAIN:
					checkVersion();
					break;
				}
			}
		};
	}

	private class InitThread extends Thread {
		@Override
		public void run() {
			try {
				Thread.sleep(500);
				Message msg = new Message();
				msg.what = W_MSG_MAIN;
				handler.sendMessage(msg);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}
}
